package com.tanhua.server.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.tanhua.autoconfig.template.FaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.commons.utils.Constants;
import com.tanhua.model.domain.UserInfo;
import com.tanhua.model.mongo.RecommendUser;
import com.tanhua.model.mongo.UserLike;
import com.tanhua.model.mongo.Visitors;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.UserInfoTVO;
import com.tanhua.model.vo.UserInfoVo;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import com.tanhua.service.RecommendUserApi;
import com.tanhua.service.UserInfoApi;
import com.tanhua.service.UserLikeApi;
import com.tanhua.service.VisitorsApi;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author げっしょく
 * @date 2021/10/23
 */

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private FaceTemplate faceTemplate;

    @DubboReference
    private VisitorsApi visitorsApi;

    @DubboReference
    private UserLikeApi userLikeApi;

    @DubboReference
    private RecommendUserApi recommendUserApi;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 保存用户信息
     * @param userInfo 用户的信息
     */
    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    /**
     * 修改用户头像
     * @param headPhoto 头像的位置
     * @throws IOException
     */
    public void saveFace(MultipartFile headPhoto) throws IOException {
        String upload = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        boolean detect = faceTemplate.detect(upload);
        if (!detect){
            throw new BusinessException(ErrorResult.faceError());
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setId(UserHolder.getId());
        userInfo.setAvatar(upload);
        userInfoApi.updateById(userInfo);
    }

    /**
     * 查询用户信息
     * @param userID 需要查询的用户的id
     * @return 该用户的信息
     */
    public UserInfoVo getUserByID(Long userID) {
        UserInfo userInfo = userInfoApi.getUserById(userID);
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtils.copyProperties(userInfo, userInfoVo);
        if (userInfo.getAge() != null) {
            userInfoVo.setAge(userInfo.getAge().toString());
        }
        return userInfoVo;
    }

    /**
     * 修改用户信息
     * @param userInfo 用户需要修改成的信息
     */
    public void updateById(UserInfo userInfo) {
        userInfoApi.updateById(userInfo);
    }

    /**
     * 修改用户头像
     * @param path 图片的路径
     * @param inputStream 输入流
     */
    public void updateHeader(String path, InputStream inputStream) {
        String upload = ossTemplate.upload(path, inputStream);
        boolean detect = faceTemplate.detect(upload);
        if (!detect) {
            throw new BusinessException(ErrorResult.faceError());
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setId(UserHolder.getId());
        userInfo.setAvatar(upload);
        userInfoApi.updateById(userInfo);
    }

/*   */
/*    public PageResult getLookMe(Integer page, Integer pagesize, String nickname) {
        //当前用户id
        Long userId = UserHolder.getId();


        String key = Constants.VISITORS_USER;
        String hashKey = userId.toString();
        //添加用户上一次查看时间
        Long l = System.currentTimeMillis();
//        redisTemplate.opsForHash().put(key, hashKey, l.toString());

        //获得访问过我的用户并判断是否为空
        List<Visitors> list = visitorsApi.getPageLookMe(page, pagesize, userId);
        if (CollUtil.isEmpty(list)) {
            return new PageResult();
        }
        //取出访问过我用户的id
        List<Long> visitorUserId = CollUtil.getFieldValues(list, "visitorUserId", Long.class);
        //通过id找出我对ta是否喜欢
        Map<Long, UserLike> map = userLikeApi.getLikes(visitorUserId, userId);
        //通过id找出用户详情
        UserInfo userInfo = new UserInfo();
        if (!StringUtils.isEmpty(nickname)) {
            userInfo.setNickname(nickname);
        }
        Map<Long, UserInfo> byUserIds = userInfoApi.getByUserIds(visitorUserId, userInfo);
        //通过id找出我与对方的缘分值
        Map<Long, RecommendUser> re = recommendUserApi.getUsers(visitorUserId, userId);
        //遍历集合
        List<UserInfoTVO> vos = new ArrayList<>();
        for (Long id : visitorUserId) {
            UserInfo userInfo1 = byUserIds.get(id);
            if (userInfo1 != null) {
                UserLike userLike = map.get(id);
                Boolean isLike = false;
                if (!ObjectUtil.isEmpty(userLike)) {
                    isLike = userLike.getIsLike();
                }
                RecommendUser recommendUser = re.get(id);
                Double score = RandomUtil.randomDouble(60.0, 95.6);
                if (ObjectUtil.isNotEmpty(recommendUser)) {
                    score = recommendUser.getScore();
                }

                UserInfoTVO vo = UserInfoTVO.init(userInfo1, isLike, score);
                vos.add(vo);
            }
        }
        return new PageResult(page, pagesize, 0L, vos);
    }*/
}
